package com.hgk.common.common.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{

	private static final int version = 2;
	private int openCount = 0;//数据库的使用线程数量
	private static DataBaseHelper databaseHelper = null;
	private static Context mContext;
	
	public DataBaseHelper(Context context) {
		super(context, DBNameConstants.DB_PUBLISH_LONG_TEXT, null, version);
	}
	public static DataBaseHelper getInstance(Context context){
		mContext=context;
		if(databaseHelper==null){
				databaseHelper = new DataBaseHelper(context);
		}
		return databaseHelper;
	}

	/**
	 * 创建长文发布数据库表
	 */
	private void createLongText(SQLiteDatabase db){
		String sql = "CREATE TABLE[" + DBNameConstants.DB_PUBLISH_LONG_TEXT+"]("+
				"_id integer primary key autoincrement,"+
				"coverUrl text,"+
				"title text,"+
				"content text,"+
				"videoUrl text,"+
				"db_id text,"+
				"topicid text,"+
				"publish_state text,"+
				"publish_type text,"+
				"arr_friend text,"+
				"arr_class text,"+
				"lesson_id text,"+
				"has_lesson text,"+
				"lesson_name text,"+
				"class_name text,"+
				"authority text,"+
				"child_count text,"+
				"teach_count text,"+
				"learn_count text,"+
				"sign_id text,"+
				"anonymous text,"+
				"to_userid text,"+
				"video_uid text,"+
				"video_path text,"+
				"nick_name text"+
				")";
		db.execSQL(sql);
	}



	@Override
	public void onCreate(SQLiteDatabase db) {
		createLongText(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        if(oldVersion<2){
//			db.execSQL("DROP TABLE IF EXISTS " + DBNameConstants.DB_PUBLISH_LONG_TEXT);
//			createLongText(db);
//		}
	}
	@Override
	public synchronized SQLiteDatabase getReadableDatabase() {
		openCount++;
		return super.getReadableDatabase();
	}
	
	@Override
	public synchronized SQLiteDatabase getWritableDatabase() {
		openCount++;
		return super.getWritableDatabase();
	}
	/**
	 * 关闭数据库不要使用DB.close(),直接使用helper.close()
	 */
	@Override
	public synchronized void close() {
		if(openCount>0){
			openCount--;
		}else{
			databaseHelper = null;
			super.close();
		}
	}
	
	/**
	 * 退出应用关闭数据
	 */
	public synchronized void exitClose(){
		if(databaseHelper!=null){
			super.close();
			openCount = 0;
			databaseHelper = null;
		}
	}

}
